package com.servlet.login.root.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 思路：先new出smartupload对象，文件上传主要藉由此对象完成传输
         * 1.   创建smartupload对象
         * 2.   获取到pagecontent缓存的文件数据请求，并传递给smartupload属性，并设置smart字符集
         * 3.   借此对象获取到文件，并读取到文件的信息，将文件信息命名成文件名，保存至指定文件夹下
         * 4.   将文件信息存入request中，转发页面到success
         */

        try {
            System.out.println("开始调用文件上传");
            SmartUpload smartUpload = new SmartUpload();

            PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(this, req, resp, null, false, 1024, true);
            smartUpload.initialize(pageContext);
            smartUpload.setCharset("utf-8");
            System.out.println("文件上传属性设置完毕");

            smartUpload.upload();
            File file = smartUpload.getFiles().getFile(0);
            System.out.println("文件上传完毕");

            String fileName = file.getFileName();
            System.out.println("filename:"+fileName);
            String contentType = file.getContentType();
            System.out.println(contentType);
            String url = "D:\\Project\\java_pro\\workspace\\Servlet4Login\\web\\uploadfilrdir\\"+fileName;
            System.out.println(url);
            file.saveAs(url,File.SAVEAS_AUTO);
            System.out.println("上传文件保存完毕");

            req.setAttribute("filename",fileName);

            req.getRequestDispatcher("fileDownLoad.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

    }
}
